---
--类名: AchView.lua
--创建日期: 2015-9-15
--创建人: 陈小虎
--功能描述: 成就视图
--修改内容:
--修改日期: 2016-8-25
--修改人: 陈小虎
--修改备注: ui修改
--
local OptionMenu = require("app.widget.optionmenu.OptionMenu")
local MoLayer = require("app.widget.MoLayer")
local TabsCheckBox = require("app.widget.TabsCheckBox")
local AvatarFactory = app:getClass("AvatarFactory")
local IconRender = require("app.widget.renders.IconRender")

local AchView = class("AchView", app.mvc.ViewBase)
AchView.VIEW_ROOT_RES = Res.AchievementScene

function AchView:init()
    cc(self):addComponent("components.behavior.EventProtocol"):exportMethods()
    UD.badge:setNum(Constant.FUNC_TYPE_ACHIEVEMENT, 0)
    --ui根节点
    self.mUINode = self._root--cc.uiloader:load(Res.AchievementScene)
    -- self:addChild(self.mUINode)
    self.mUINode:setContentSize(cc.size(display.width,display.height))
    ccui.Helper:doLayout(self.mUINode)

    self.panelCount = self.mUINode:findChild("Panel/count")
    self.panelAchieve = self.mUINode:findChild("Panel/achieve")
    self.panelShop = self.mUINode:findChild("Panel/shop")
    self.panelShop:findChild("Panel/Panel_gold"):setVisible(false)
    self.panelShop:findChild("Panel/Panel_money"):setVisible(false)

    self.panelCount:hide()
    self.panelShop:hide()

    self:addCloseListener()

    self:loadTypeTree()
    self:initAchList()

    self:initMainUI()
    self:initAchListView()
    self:initOverviewPanel()
    self:initTabs()

    self:onClearView(function()
        EM:removeByName(AchievementManager.GoodsChangeEventName)
        EM:removeByName(AchievementManager.StatisticsChangeEventName)
        EM:removeByName(AchievementManager.AchDataChange)
        if self._walletHandler then
            UD:unChanged("wallet", self._walletHandler)
        end

        self.achGroupNode:release()
        self.achItemNode:release()
        self.achNode:release()
        self.achTubNode:release()
        self.achShopNode:release()

        AchievementManager.newAch = {}
    end)
    EM:on(AchievementManager.GoodsChangeEventName, function()      
        self:refreshShopRedPoint()
    end)

    EM:on(AchievementManager.AchDataChange, function()
        self.typeTree = AchievementManager:getTypeTree()
        self.typeContents = AchievementManager:getAchList()
        self:initOverviewPanel(true)
    end)

    self:registerViewEvent({
        {name = ViewEvent.AchieveShop_BuyGoods, callback = handler(self, self.initMainUI)}
    })
    AchievementManager:queryGoods()
end

function AchView:addCloseListener()
    local btnClose = self.mUINode:findChild("Panel/Button_close")
    btnClose:addClickEventListener(function(sender)        
        self:dispatchEvent({name = "ACH_UI_CLOSE"})
    end)
end

function AchView:seek(aName, aParent)
    return ccui.Helper:seekWidgetByName(aParent, aName)
end

function AchView:setCurrencyEnable(b)
    self.goldPanel = self.mUINode:findChild("Panel/Panel_achieve")
    self.magicPanel = self.mUINode:findChild("Panel/Panel_gold")
    self.goldPanel:setVisible(b)
    self.magicPanel:setVisible(b)
end

function AchView:initMainUI()
    self:setCurrencyEnable(false)
    local function showPanelTips(panel, param)
        local boundingBoxTemp = panel:getBoundingBox()
        local worldPosTemp = panel:getParent():convertToWorldSpace( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
        boundingBoxTemp.x = worldPosTemp.x
        boundingBoxTemp.y = worldPosTemp.y
        param.boundingBox = boundingBoxTemp
        app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params = param})
    end

    local function setPanel(panel, currency)
        panel:setVisible(true)
        local iconNode = panel:getChildByName("icon")
        local numNode = panel:getChildByName("num")
        local szValues = string.split(currency, "|")

        local param = {}
        local icon = nil

        if #szValues == 1 then -- 货币
            local id = tonumber(szValues[1])
            icon = GD:getResIcon(id)
            if id == 90 then -- 成就点
                numNode:setString(UD.player.achievementPoint)
            else
                numNode:setString( UD:getDaibiValue( id ))
            end

            param.itemId = id
            param.tipsType = Enums.TipsType.daibi
        else
            if tonumber(szValues[1]) == Enums.lootType.item then -- 物品
                local id = tonumber(szValues[2])
                local conf = GD:queryItemById(id)
                icon = string.format("%s%s.png", Res.itemPath, conf.icon) -- 设置图标
                numNode:setString(UD:getItemAmountByTid(id))

                param.itemId = id
                param.tipsType = Enums.TipsType.item
            end
        end
        -- 设置图标
        if icon then
            iconNode:loadTexture(icon)
        end
        -- 添加监听事件显示tips
        panel:addTouchEventListener(function(sender, eventType)
            if eventType ~= 2 then return end
            showPanelTips(sender, param)
        end)
    end

    local shopConfig = GD:queryShopById(AchievementManager.shopId)
    local currencys = string.split(shopConfig.currency, ";")
    if #currencys > 0 then
        setPanel(self.goldPanel, currencys[1])
    end
    if #currencys > 1 then
        setPanel(self.magicPanel, currencys[2])
    end
end 

function AchView:loadTypeTree()
    if not self.typeTree then
        self.typeTree = AchievementManager:getTypeTree()
    end 

    return self.typeTree
end

function AchView:initAchList()
    self.typeContents = AchievementManager:getAchList()

    return self.typeContents
end 

function AchView:getAchListByTypeId(aSubTypeId)
    return self.typeContents[aSubTypeId] or {}
end 

function AchView:initAchListView()
    self.achGroupNode = cc.CSLoader:createNode(Res.AchievementTypeNode)
    self.achItemNode = cc.CSLoader:createNode(Res.AchievementSubTypeNode)
    self.achNode = cc.CSLoader:createNode(Res.AchievementNode)
    self.achTubNode = cc.CSLoader:createNode(Res.AchievementTubTypeNode)
    self.achShopNode = cc.CSLoader:createNode(Res.AchievementShopItem)
    
    self.achGroupNode:retain()
    self.achItemNode:retain()
    self.achNode:retain()
    self.achTubNode:retain()
    self.achShopNode:retain()

    self.achGroupNode:setAnchorPoint(cc.p(0, 1))
    self.achItemNode:setAnchorPoint(cc.p(0, 1))

    self.achTypeList = self.panelAchieve:findChild("Panel/ListView_1")
    self.achContentList = self.panelAchieve:findChild("Panel/ListView_2")
    self.overviewPanel = self.panelAchieve:findChild("Panel/Panel_sum")
    self.lastTypeButton = nil

    self.achTypeList:setGravity(ccui.ListViewGravity.left)
    self.achTypeList:setItemsMargin(0)
    self.selColor = cc.c3b(255,225,132)
    self.idlColor = cc.c3b(172,165,154)
    
    self.setLastSubTypeBtn = function (btn , lbl)
        if self.lastSubTypeBtn then 
            self.lastSubTypeBtn:setTouchEnabled(false)
            self.lastSubTypeBtn:setBright( true )
        end

        btn:setTouchEnabled(false)
        btn:setBright(false)
        self.lastSubTypeBtn = btn 

        if self.lastSubTypeLbl then
            self.lastSubTypeLbl:setTextColor(self.idlColor)
        end

        if lbl then
            lbl:setTextColor(self.selColor)
        end
        self.lastSubTypeLbl = lbl
    end 

    local function GetSubTypeItem()
        local i = self.achItemNode:clone()
        i:setContentSize(ccui.Helper:seekWidgetByName(i, "Panel"):getContentSize())

        i.lblName = self:seek("name", i)
        i.btnSelect = self:seek("selected_btn", i)
        i.panel = self:seek("Panel", i)
        i.lblName:setTextColor(self.idlColor)
        i.btnSelect:setPressedActionEnabled(false)
        i.btnSelect:setTouchEnabled(false)

        i.selectSubType = function()
            self.setLastSubTypeBtn(i.btnSelect, i.lblName)
            self:showSubTypeContent(i._data.ID)
        end 

        i.panel:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                i.selectSubType()
            end
        end)

        i.setData = function(d)
            i._data = d
            i.lblName:setString(L(d.title))
        end 

        return i
    end

    local function checkLastTypeBtn(aBtn)
        if self.lastTypeButton and self.lastTypeButton ~= aBtn then
            self.lastTypeButton.content.btnSelect:setTouchEnabled(true)
            self.lastTypeButton.content.btnSelect:setBright(true)
            self.lastTypeButton.colapse()
            self.lastTypeButton.content.lblName:setTextColor(self.idlColor)
        end 
        self.lastTypeButton = aBtn 

        self.lastTypeButton.content.btnSelect:setTouchEnabled(false)
        self.lastTypeButton.content.btnSelect:setBright(false)
        self.lastTypeButton.content.lblName:setTextColor(self.selColor)
    end 

    local function GetTypeItem()
        local i = self.achGroupNode:clone()
        local l = ccui.Layout:create()
        l:setLayoutType(ccui.LayoutType.VERTICAL)
        i:setContentSize(ccui.Helper:seekWidgetByName(i, "Panel"):getContentSize())
        l:setContentSize(i:getContentSize())
        l:setBackGroundColor(cc.c3b(78, 78, 78))

        i.imgUp = self:seek("img_2", i):show()
        i.imgDown = self:seek("img_1", i):hide()
        i.lblName = self:seek("name", i)
        i.btnSelect = self:seek("selected_btn", i)    
        i.btnSelect:setPressedActionEnabled(false)
        i.lblName:setTextColor(self.idlColor)

        i:findChild("Panel"):setBackGroundColorType(ccui.LayoutBackGroundColorType.none)
        i:findChild("Panel"):addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                i.selectItem()
            end
        end)
        
        i.selected = false
        l.setSelected = function(b)
            i.imgUp:hide()
            i.imgDown:hide()
            if #i._data.children > 0 then
                if b then
                    i.imgDown:show()
                else
                    i.imgUp:show()
                end
            end
            i.selected = b 
            if #i._data.children == 1 then
                i.imgUp:hide()
                i.imgDown:hide()
            end
        end 

        i.selectItem = function(aAchCfg)
            self.overviewPanel:hide()
            self.achContentList:show()
            AchievementManager.newAch = {}
            self:refreshOverViewRedPoint()

            checkLastTypeBtn(l)

            i.selected = not i.selected

            if i.selected then
                if #i._data.children == 1 and checknumber(i._data.children[1].titleshow) == 0 then
                    self:showSubTypeContent(i._data.children[1].ID)
                else
                    l.extend(aAchCfg)
                end
            else 
                l.colapse()
            end 
        end
        i.btnSelect:addClickEventListener(function()
                i.selectItem()
            end)

        l.setData = function(d)
            i._data = d
            i.lblName:setString(L(d.title))
            if #d.children <= 1 then
                i.imgUp:hide()
                i.imgDown:hide()
            end
        end

        l:addChild(i)
        l.content = i
        l.getChildren = function()
            if l._children then
               return l._children
            end

            l._children = {}
            l._childrenHeight = 0
            for k, v in ipairs(i._data.children) do
                local sub = GetSubTypeItem()
                sub.setData(v)

                l:addChild(sub)
                l._childrenHeight = l._childrenHeight + sub:getContentSize().height
                l._children[#l._children + 1] = sub
            end

            return l._children
        end

        l.showChildren = function(b)
            for k, v in pairs(l.getChildren()) do
                v:setVisible(b)
            end
        end

        l.colapse = function()
            l:setContentSize(i:getContentSize())
            l.showChildren(false)
            self.achTypeList:requestRefreshView()
            self.achTypeList:forceDoLayout()
            l.setSelected(false)
            l:setBackGroundColorType(ccui.LayoutBackGroundColorType.none)
        end 

        l.extend = function(aAchCfg)
            l.showChildren(true)
            l:setContentSize(cc.size(i:getContentSize().width, i:getContentSize().height + l._childrenHeight))
            self.achTypeList:requestRefreshView()
            self.achTypeList:forceDoLayout()
            l.setSelected(true)

            if aAchCfg then
                for _, v in ipairs(l._children) do
                    if v._data.ID == AchievementManager:getSubType(aAchCfg.belong) then
                        l:setBackGroundColorType(1)
                        v:selectSubType()
                        break
                    end
                end
            else
                --选第一个子类型
                if l._children and l._children[1] then
                    l:setBackGroundColorType(1)
                    l._children[1]:selectSubType()
                end 
            end
        end

        l.selectSubTypeByAch = function(achCfg)
            for k,v in ipairs(l._children) do
                if achCfg.ID == v._data.ID then
                    v:selectSubType()
                end
            end
        end
        
        return l
    end

    local i = GetTypeItem()
    i.setData({title=L("lua_code_text_384"),children={}})
    i.content.btnSelect:addClickEventListener(function()
        self.overviewPanel:show()
        self.achContentList:hide()
        self:refreshOverViewRedPoint()
        checkLastTypeBtn(i)
    end )
    i.content.selectItem = function()end
    checkLastTypeBtn(i)

    self.achTypeList:pushBackCustomItem(i)

    self.typeMapNode = {}
    for k, v in ipairs(self.typeTree.children) do
        local i = GetTypeItem()
        i.setData(v)
        self.typeMapNode[v.ID] = i
        self.achTypeList:pushBackCustomItem(i)
    end
end

function AchView:gotoAch(achCfg)
    self.typeMapNode[AchievementManager:getRootType(achCfg.belong)].content.selectItem(achCfg)
    local an = self.achContentList.mapNodes[achCfg.ID]
    
    local off  = self.achContentList:getInnerContainerSize().height - self.achContentList:getContentSize().height
    if off > 0 then
        local off2 = math.max(0, off - (self.achContentList:getInnerContainerSize().height - math.abs(an:getPositionY() + 101)))
        self.achContentList:jumpToPercentVertical(math.max(0, math.min(100, 100 * (1-off2/off))))
    end
end

function AchView:showSubTypeContent(aSubTypeId)
    if self.achContentList.currentTypeId == aSubTypeId then
        return
    end

    self.achContentList.currentTypeId = aSubTypeId

    local function loadTubType(aTubTypeId)
        local alist = self:getAchListByTypeId(aTubTypeId)
        -- 排序
        local function GetAchItem()
            local i = self.achNode:clone()
            i:setContentSize(ccui.Helper:seekWidgetByName(i, "Panel"):getContentSize())
            
            i.lblName = i:findChild("Panel/name")
            i.lblNameGot = i:findChild("Panel/name_1")
            i.lblDesc = self:seek("Text", i)
            i.lblAchNum = self:seek("achieve_num", i)
            i.btnShare = self:seek("Button_go", i)
            i.imgIcon = self:seek("icon", i)
            i.imgIconMask = self:seek("icon_mask", i)   
            i.imgIconMask:show()         

            i.progressBar = self:seek("LoadingBar", i)
            i.progressText = i:findChild("Panel/bar/num")
            i.notAch = i:findChild("Panel/achieve_no")
            i.Ached = i:findChild("Panel/achieve_own")
            i.bgBtn = i:findChild("Panel/Panel_bg/bg01")
            i.bgImg = i:findChild("Panel/Panel_bg/bg05")
            i.bgIcon = i:findChild("Panel/Panel_bg/bg04")

            self:seek("bg01", i):setZoomScale(0)
            self:seek("Button_go", i):addTouchEventListener(function()
                local status = 0
                if AchievementManager:isAchievementFinished(i._data.ID) then
                    status = 1
                end
                app:sendMsg("IMRoomController", "shareItem", Enums.TipsType.achieve, i._data.ID, status)
            end )

            i.setIcon = function()
            end 

            --监听任务状态变化
            i.setData = function(d)
                i._data = d 
                i.lblDesc:setString(L(d.desc))
                
                i._task = AchievementManager:getTaskById(i._data.taskID)
                i.imgIcon:loadTexture("art/achieve/"..d.icon..".png")

                if i._task then 
                    local curCnt = 0
                    local needCnt = 0
                    for _, v in pairs(i._task.taskProgress) do
                        if v and v.Num and v.NeedNum then
                            curCnt = curCnt + math.min(v.Num, v.NeedNum)
                            needCnt = needCnt + v.NeedNum
                        end
                    end
                    
                    local p = i._task:getDefaultProgress()
                    if p then 
                        i.setProgress(curCnt, needCnt)
                    end 
                    i.lblAchNum:setString(tostring(GD:getAchievementPointById(i._data.ID)))
                    if i.notAch then
                        i.notAch:show()
                    end
                    if i.Ached then
                        i.Ached:hide()
                    end

                    i.bgBtn:setTouchEnabled(false)
                    i.bgIcon:setColor(cc.c3b(102, 96, 85))
                    i.lblAchNum:setColor(cc.c3b(178, 178, 178))
                    if AchievementManager:getTaskById(i._data.taskID) and 
                      (AchievementManager:getTaskById(i._data.taskID):isFinished() or AchievementManager:getTaskById(i._data.taskID):isRewarded()) then
                        i.lblName:hide()
                        i.lblNameGot:show()
                        i.lblNameGot:setString(L(d.name))
                        i.imgIconMask:hide()
                        i.bgBtn:setTouchEnabled(false)
                        i.bgBtn:setBright(false)
                        i.bgImg:setColor(cc.c3b(171, 112, 68))
                        i.lblAchNum:setColor(cc.c3b(255,225,132))
                        i.bgIcon:setColor(cc.c3b(134, 88, 51))
                        if i.notAch then
                            i.notAch:hide()
                        end
                        if i.Ached then
                            i.Ached:show()
                        end
                        i.progressBar:hide()
                        i:findChild("Panel/bar/bar_bg"):hide()
                        i.progressText:hide()
                        if i:findChild("Panel/tip") then
                            i:findChild("Panel/tip"):show()
                            i:findChild("Panel/tip"):setString(tostring(os.date("%Y-%m-%d", AchievementManager:getTaskById(i._data.taskID).completeStamp)..L("lua_code_text_101")))
                        end
                    else
                        i.lblName:show()
                        i.lblNameGot:hide()
                        i.lblName:setString(L(d.name))
                        i.bgImg:setColor(cc.c3b(169, 139, 84))
                        i.lblDesc:setOpacity(80)
                    end
                else
                    print("task not exist:", i._data.taskID)
                end 
            end

            i.setProgress = function(cur, total)
                if cur > total then cur = total end 
                if cur < 0 then cur = 0 end 
                i.progressBar:setPercent(cur/total*100)
                i.progressText:setString(tostring(cur).."/"..tostring(total))
            end 

            return i 
        end 

        for k, v in ipairs(alist) do
            local i = GetAchItem()
            i.setData(v)
            self.achContentList.mapNodes[v.ID] = i
            self.achContentList:pushBackCustomItem(i)
        end 
    end

    self.achContentList:removeAllChildren()
    self.achContentList.mapNodes = {}
    
    local marginN = ccui.Layout:create()
    marginN:setContentSize(cc.size(10, 7))
    self.achContentList:pushBackCustomItem(marginN)
    local tv = self.typeTree.entries[aSubTypeId]
    local function getTubItem(data)
        local ret = self.achTubNode:clone()
        ret:setContentSize(self:seek("Panel", ret):getContentSize())
        self:seek("name", ret):setString(L(data.title))
        return ret
    end
    for k, v in pairs(tv.children) do 
        if v then 
            -- self.achContentList:pushBackCustomItem(getTubItem(v))
            loadTubType(v.ID)
        end 
    end 
    self.achContentList:forceDoLayout()
    self.achContentList:jumpToTop()
end 

function AchView:initOverviewPanel(f)
    if self.overviewG and not f then 
        return
    end 

    self.allPb = self.panelAchieve:findChild("Panel/Panel_sum/Panel_collect/bar_all/LoadingBar")
    self.allLbl = self.panelAchieve:findChild("Panel/Panel_sum/Panel_collect/bar_all/num")

    self.allLbl:setString(tostring(checkint(UD.player.achievementPoint)).."/"..tostring(AchievementManager.totalPoint))
    self.allPb:setPercent(100 * checkint(UD.player.achievementPoint) / AchievementManager.totalPoint)

    self.curPointLbl = self.panelAchieve:findChild("Panel/Panel_sum/Panel_tlt/num")  
    self.curPointLbl:setString(tostring(checkint(UD.player.achievementPoint)))
    local ids = {1, 2, 3, 4}

    self.overviewG = {}
    for i = 1, 6 do
        local n = self.panelAchieve:findChild("Panel/Panel_sum/Panel_collect/bar_"..tostring(i))
        local t = {
            p = n:findChild("LoadingBar"),
            l = n:findChild("num"),
            t = n:findChild("tlt")
        }

        if ids[i] then
            local totalP = checknumber(self.typeTree.entries[ids[i]].sumPoint )
            local curP = checknumber(self.typeTree.entries[ids[i]].sumCurPoint)

            t.p:setPercent(100 * curP / totalP)
            t.l:setString(tostring(curP).."/"..tostring(totalP))
            t.t:setString(L(self.typeTree.entries[ids[i]].title))

            self.overviewG[i] = t
        else
            n:hide()
        end
    end 
        
    self.panelAchieve:findChild("Panel/Panel_sum/tips"):setVisible(#AchievementManager.gotAches <= 0)
    
    local icons = {}
    for i = 1, 5 do
        local icon = self.panelAchieve:findChild("Panel/Panel_sum/Panel_bom/icon_"..tostring(i))
        local nm = self.panelAchieve:findChild("Panel/Panel_sum/Panel_bom/icon_"..tostring(i).."/name")
        if AchievementManager.gotAches[i] then
            icon:show()
            icon:findChild("Panel/selected"):hide()
            icon:findChild("Panel/level"):hide()
            icon:findChild("Panel/Panel_num"):hide()
            icon:findChild("Panel/selected"):hide()
            icon:findChild("Panel/icon"):loadTexture("art/achieve/"..AchievementManager.gotAches[i].icon..".png")
            local ach = AchievementManager.gotAches[i]
            icon:findChild("Panel"):setTouchEnabled(true)
            icon:findChild("Panel"):addTouchEventListener(function(sender, eventType)
                if eventType == ccui.TouchEventType.ended then
                    self:gotoAch(ach)
                end
            end)
            if nm then
                nm:setString(string.uomitstr(L(AchievementManager.gotAches[i].name), 6))
            end
        else
            icon:hide()
        end
        table.insert(icons, icon)
    end

    local w = icons[1]:findChild("Panel"):getContentSize().width + 22

    local gw = math.max((5 - #AchievementManager.gotAches), 0) * w * 0.5
    for i = 1, 5 do
        local xx = (i - 1) * w
        local yy = icons[i]:getPositionY()

        icons[i]:setPosition(cc.p(xx + gw, yy))
    end

    self:refreshOverViewRedPoint()
end 

function AchView:refreshOverViewRedPoint()
    local hasNew = false
    for i = 1, 5 do
        local icon = self.panelAchieve:findChild("Panel/Panel_sum/Panel_bom/icon_"..tostring(i))
        local na = AchievementManager.gotAches[i]
        if na then
            if checkbool(AchievementManager.newAch[na.ID]) then
                icon:findChild("Panel/dot"):setVisible(true)
                hasNew = true
            else
                icon:findChild("Panel/dot"):setVisible(false)
            end            
        end
    end
    self.mUINode:findChild("Panel/Panel_tab/selected_btn_1/dot"):setVisible(hasNew)
end

-- data = {
--     {btn=,onTabSelected=,},
--     {btn=,onTabSelected=,},
-- }
function AchView.CreateTabGroup(data)
    local btns = {}
    
    local function createGroup(aBtns)
        local g = {btns = aBtns}
        g.showname = function(btn, b)
            if btn:findChild("name_1") then
                btn:findChild("name_1"):setVisible(not b)
            end
            if btn:findChild("name_2") then
                btn:findChild("name_2"):setVisible(b)
            end
        end

        g.select = function(idx)
            g.reset()
            aBtns[idx]:setTouchEnabled(false)
            aBtns[idx]:setBright(false)
            g.showname(aBtns[idx], true)
        end
        g.reset = function()
            for i, b in ipairs(aBtns) do
                b:setTouchEnabled( true )
                b:setBright( true )
                g.showname(b, false)
            end
        end
        g.selectTab = function(idx)
            aBtns[idx].onClickEvt()
        end
        return g 
    end

    local group = createGroup(btns)

    for i, v in ipairs(data) do
        v.btn:show()
        v.btn.onClickEvt = function()
            if v.onTabSelected then
                v.onTabSelected()
            end
            group.select(i)
        end
        v.btn:addTouchEventListener(v.btn.onClickEvt)
        table.insert(btns, v.btn)
    end

    return group
end

function AchView:initTabs()
    local btns = {}
    table.insert(btns, self.mUINode:findChild("Panel/Panel_tab/selected_btn_1"))
    table.insert(btns, self.mUINode:findChild("Panel/Panel_tab/selected_btn_2"))
    table.insert(btns, self.mUINode:findChild("Panel/Panel_tab/selected_btn_2_0"))

    local function hideAll()
        self.panelCount:hide()
        self.panelAchieve:hide()
        self.panelShop:hide()
        self:refreshOverViewRedPoint()
    end 
    local group = self.CreateTabGroup({
        {btn = btns[1], onTabSelected=function()
            hideAll()
            self:setCurrencyEnable(false)
            self.panelAchieve:show()
        end},
        {btn = btns[2], onTabSelected=function()
            AchievementManager.newAch = {}
            hideAll()
            self:setCurrencyEnable(true)
            self:initShopPanel()
            self.panelShop:show()
            AchievementManager.canBuyCount = AchievementManager.tempCanBuyCount
        end},
        {btn = btns[3], onTabSelected=function()
            AchievementManager:queryStatistics()
            AchievementManager.newAch = {}
            hideAll()
            self:setCurrencyEnable(false)
            self:initStatisticPanel()
            self.panelCount:show()
        end},
    })

    self.selectTab = function(this, aTab, itemType, itemId)
        if aTab == 1 or aTab == 2 then            
            group.selectTab(aTab)
            if itemType ~= nil and itemId ~= nil then
                self._itemInfo = {itemType, itemId}
            end            
        else
            group.selectTab(1)
        end
    end
end

function AchView:getStatisticTree()
    if self.statisticTree then 
        return self.statisticTree
    end 

    self.statisticTree = {
        categorys = {}
    }
    local achs = GD:getAchievementStatistics()
    for k, v in pairs(achs) do
        local tv = v:getValues()
        tv.ID = tonumber(tv.ID)
        tv.limit = tonumber(tv.limit)
        tv.order = tonumber(tv.order)
        tv.category = tonumber(tv.category)
        tv.condition = checknumber(tv.condition)

        local cs = self.statisticTree.categorys[tv.category] or {}

        cs[#cs + 1] = tv 

        self.statisticTree.categorys[tv.category] = cs 
    end 
    for k, v in pairs(self.statisticTree.categorys) do
        table.sort(v, function(a, b)
            return a.order > b.order
        end)
    end
    return self.statisticTree
end 

function AchView:initStatisticPanel()
    if self.statisticPanelInited then
        return 
    end 
    self.statisticPanelInited = true 

    self.spName = self.panelCount:findChild("Panel/Panel_player/name")
    self.spName:setString(UD.player.name)

    self.spLevel = self.panelCount:findChild("Panel/Panel_player/lv_num")
    self.spLevel:setString(tostring(UD.player.level))

    self.classIcon = self.panelCount:findChild("Panel/Panel_player/job_icon")
    local classIconPath = GD:getClassIcon( UD.player.classID, 2 )
    self.classIcon:loadTexture( classIconPath )

    local params = UD:getAvatarParams()

    params.mountID = 0 -- 不显示坐骑

	local heroHolder = self.panelCount:findChild("Panel/Panel_player/Node_position")
		self:performWithDelay(function()
			params.inBattle = false
			local hero = AvatarFactory.createHero(params)
			hero:setTag(0)
            hero:playAni({name="mapidle",next="mapidle"})
            heroHolder:addChild(hero)
		end, 0.2)

    self.spDetailPanel = self.panelCount:findChild("Panel/ScrollView")
    local pv = self.spDetailPanel
    local renders = {}
    pv:setBounceEnabled(false)
    pv:setInertiaScrollEnabled(false)

    self.statisticPage = cc.CSLoader:createNode(Res.AchievementStatisticPage)
    self.statisticItem = cc.CSLoader:createNode(Res.AchievementStatisticItem)
    local function getPage(v, ptype)
        local cnt = math.max(#v  + 2, 8)
        local pageSize = cc.size(608, 300 + (cnt - 8)*27)

        local w = ccui.Layout:create()
        w:setContentSize(pageSize)

        local p = self.statisticPage:clone()
        local BgNode = p:findChild("Panel/bg"):clone()
        BgNode:setContentSize(pageSize)
        BgNode:setAnchorPoint(cc.p(0, 1))
        BgNode:setPosition(cc.p(-1, pageSize.height))

        local frame = BgNode:findChild("Image")
        frame:setAnchorPoint(cc.p(0, 1))
        frame:setContentSize(cc.size(pageSize.width - 22, pageSize.height - 22))
        frame:setPosition(cc.p(11, pageSize.height - 11))

        local icnBg = BgNode:findChild("Image_2")
        icnBg:setPosition(cc.p(icnBg:getPositionX()+5, pageSize.height - 170))
        w:addChild(BgNode)     
        
        local HeadNode = p:findChild("Panel"):clone()
        HeadNode:findChild("bg"):hide()
        HeadNode:setAnchorPoint(cc.p(0, 1))
        HeadNode:setPosition(cc.p(0, pageSize.height))

        w.typeIcon = HeadNode:findChild("head")
        w.littleIcon = HeadNode:findChild("icon")
        w.typeName = HeadNode:findChild("name")
        HeadNode:findChild("data"):hide()
        w:addChild(HeadNode)
        ccui.Helper:doLayout(w)

        if app:getCurrentLanguage() == "EN" then
            w.typeIcon:setScale(0.8)
            w.typeIcon:setPosition(w.typeIcon:getPositionX() + 10, 
                                w.typeIcon:getPositionY() + 10)
    
            icnBg:setScale(0.8)
            icnBg:setPosition(icnBg:getPositionX() + 10, 
                        icnBg:getPositionY() + 10)
        end

        w.typeIcon:loadTexture("art/achieve/achievement_statistics_class_"..tostring(ptype)..".png")
        local tconfig = GD:getAchievementStatisticsTypeConfig(ptype)
        if tconfig.resource2 then
            w.littleIcon:loadTexture("art/achieve/"..tconfig.resource2..".png")
        end        
        w.typeName:setString(L(tconfig.name))
        -- -- tconfig.resource
        local lv = ccui.Layout:create()
        lv:setPosition(46 , pageSize.height - 84)
        lv:setAnchorPoint(cc.p(0, 1))

        local itemHeight = 0 -- lv中每一项高度
        local lvHeight = 0 -- lv总高度
        local count = 0
        for _, itemCfg in ipairs(v) do 
            local i = self.statisticItem:clone()
            i.lblTitle = self:seek("Text", i)
            i.lblCount = self:seek("num", i)
            i.panel = self:seek("Panel", i)
            i.panel:setTouchEnabled(false)
            i.panel:setPosition(cc.p(i.panel:getPositionX() + 10, i.panel:getPositionY()))
            i:setContentSize(i.panel:getContentSize())

            i.lblTitle:setString(L(itemCfg.name))
            
            local function setStatisticNum()
                local curNum = checknumber(AchievementManager.statistics[itemCfg.ID])
                if checknumber(itemCfg.ID) == 6 then --在线时间（小时，不足1小时按1小时算）
                    curNum = math.floor(math.max(3600, curNum) / 3600)
                end
                
                i.lblCount:setString(tostring(curNum))
            end
            EM:on(AchievementManager.StatisticsChangeEventName, function()
                setStatisticNum()
            end)
            setStatisticNum()
            itemHeight = i:getContentSize().height
            count = count + 1
            i:setPosition(cc.p(0, (itemHeight+2)*(count-1)))
            lv:addChild(i)
        end
        lvHeight = itemHeight*count + (count-1)*2
        lv:setContentSize((cc.size(pageSize.width, lvHeight)))  
        w:addChild(lv)
        return w 
    end 

    local st = self:getStatisticTree()

    for k, v in pairs(st.categorys) do 
        local np = getPage(v, k)
        pv:addChild(np)
        table.insert(renders, np)
    end

    local heightCount = 0
    local renderHeight = 0
    local renderPosY = 0
	for _, render in ipairs(renders) do
        heightCount = heightCount + render:getContentSize().height
    end
    renderPosY = heightCount
    for _, render in ipairs(renders) do
		renderHeight = render:getContentSize().height
        renderPosY = renderPosY - renderHeight
        render:setPositionY(renderPosY)
    end
    local width = pv:getContentSize().width
    pv:setInnerContainerSize(cc.size(width, heightCount))
    pv:jumpToTop()
end 

function AchView:initShopPanel()
    self:showShopRedPoint(false)
    self:CreateShopPanel()
end

function AchView:CreateShopPanel()    
    if self.shopInited then
        return 
    end 
    self.shopInited = true 
    self.showShop = function(b)
        self.panelShop:findChild("Panel/Panel_top"):setVisible(b)
        self.panelShop:findChild("Panel/ListView"):setVisible(b)
        self.panelShop:findChild("Panel/Panel_tips"):setVisible(not b)
    end
    self.panelShop:findChild("Panel/Panel_money"):setVisible(false)

    local curName = self.panelShop:findChild("Panel/Panel_top/name")
    local iconRoot = self.panelShop:findChild("Panel/Panel_top/icon")
    local lvIconRender = IconRender.create(iconRoot)

    local tips1 = self.panelShop:findChild("Panel/Panel_top/tips_1")
    local tips2 = self.panelShop:findChild("Panel/Panel_top/tips_2")
    local descText = self.panelShop:findChild("Panel/Panel_top/text")
    self.panelShop:findChild("Panel/Panel_renown"):hide()
    self.panelShop:findChild("Panel/Panel_guild"):hide()
    
    local conditionPanel = self.panelShop:findChild("Panel/Panel_condition")
    local achievePanel = self.panelShop:findChild("Panel/Panel_achieve")
    local needLbl = achievePanel:getChildByName("text")
    local btnBuy = achievePanel:getChildByName("Button_buy")
    local btnLook = achievePanel:getChildByName("btn_look")
    local panelNum = achievePanel:getChildByName("Panel_num")
    local dot = panelNum:getChildByName("dot")
    local curPrice = panelNum:getChildByName("num")
    local goldIcon = panelNum:getChildByName("gold")
    if self._originalX == nil then
        self._originalX = btnBuy:getPositionX()
        self._originalMidX = achievePanel:getContentSize().width / 2
    end

    local curCount = 1
    local maxCount = 1
    local onePrice = 1
    local curItemId = 0
    local curCondition = 0
    local curConditionType = 0
    local currentBtn = nil
    local ct = self.currencyType
    local curData = nil
    local avatarData = nil
    self.panelShop:findChild("Panel/Panel_top/icon"):findChild("Panel/selected"):hide()

    self.panelShop:findChild("Panel/Panel_top/icon"):findChild("Panel/level"):hide()

    local function setCurrentItem(aItemId, aData, aBtn, aEnougn)
        local itemData = aData.itemData
        curData = aData
        if currentBtn then
            currentBtn:setTouchEnabled(true)
            currentBtn:setBright( true )
        end
        currentBtn = aBtn
        currentBtn:setTouchEnabled(false)
        currentBtn:setBright( false )
        curItemId = aData.ID
        if aData.name then
            curName:setString(L(aData.name))
        else
            curName:setString(itemData:getName())
        end
        lvIconRender:setData(itemData)
        lvIconRender:setTipEnable(true)
        lvIconRender:setTipUnShowOrigin(true)
        lvIconRender:setComparedTipEnabled(true)
        
        tips1:setString(itemData:getTypeName())
        tips2:show()

        local bindType = itemData:getBindType()
        if bindType == 0 then
            tips2:setString(L("tradable"))
        elseif bindType == 1 then
            tips2:setString(L("lua_code_text_296"))
        elseif bindType == 2 then
            tips2:setString(L("lua_code_text_320"))
        else
            tips2:hide()
        end 

        descText:setString(itemData:getDesc())
        local costList = string.split(aData.cost, ";")
        if #costList == 1 then
            achievePanel:setVisible(true)
            conditionPanel:setVisible(false)
            btnBuy = achievePanel:getChildByName("Button_buy")
            btnLook = achievePanel:getChildByName("btn_look")
            onePrice = checknumber(string.split(costList[1], "|")[3])
            curPrice:setString(onePrice)
            if curConditionType == 6 then
                needLbl:setString(string.format(L("lua_code_text_150"), tostring(curCondition)))
            else
                needLbl:setString(L("achshop_cond_achid_buy")..L(AchievementManager.achMap[checknumber(curCondition)].name))
            end
            if aEnougn then
                needLbl:setColor(cc.c3b(0xff, 0xe1, 0x84))
            else
                needLbl:setColor(cc.c3b(255, 105, 85))
            end
        else
            achievePanel:setVisible(false)
            conditionPanel:setVisible(true)
            btnBuy = conditionPanel:getChildByName("Button_buy")
            btnLook = conditionPanel:getChildByName("btn_look")
            --originalX = btnBuy:getPositionX()
            --originalMidX = conditionPanel:getContentSize().width / 2
            for i = 1, 3 do
                local name = "icon_"..i
                local iconNode = conditionPanel:getChildByName(name)
                if iconNode then
                    iconNode:setVisible(false)
                end 
            end
            local uWidth = conditionPanel:getContentSize().width
            for i, costData in ipairs(costList) do
                local cost = string.split(costData, "|")
                local item = UD:parseLootToBagItem({type = tonumber(cost[1]), id = tonumber(cost[2]), num = tonumber(cost[3])})
                local name = "icon_"..i
                local iconNode = conditionPanel:getChildByName(name)
                if iconNode then
                    iconNode:setVisible(true)
                    local uiItem = IconRender.create(iconNode)
                    uiItem:setData(item)
			        uiItem:setTipEnable(true)
			        uiItem:setNumBgVisible(true)
                    local hasNum = UD:getNumByRenderData(item)
                    local isEnough = hasNum >= item.amount
                    uiItem:setNumString(hasNum .. "/" .. item.amount)
                    if not isEnough then
                        uiItem:setNumberColor(display.COLOR_RED)
                    else
                        uiItem:setNumberColor(display.COLOR4_GREEN)
                    end
                    uiItem:updateNumberSize()
                    local sWidth = iconNode:getContentSize().width + 10
                    local posY = iconNode:getPositionY()
                    local sx = (uWidth - #costList * sWidth) / 2 + (i - 1) * sWidth + 5
			        uiItem:setPosition(cc.p(sx,posY))
                end
            end
        end

        -- 是否可以预览
        local bShow = false
        if aData.itemData and aData.itemData.isClassAvatarEnable then
            bShow, avatarData = aData.itemData:isClassAvatarEnable()
        end
        if bShow then
            btnLook:setVisible(true)
            btnBuy:setPositionX(self._originalX)
        else
            btnLook:setVisible(false)
            btnBuy:setPositionX(self._originalMidX)
        end
        btnLook:addClickEventListener(function(sender)
            EM:notify("avatarPreview", avatarData)
        end)
        btnBuy:addClickEventListener(function(sender)
            local param = {goodsId = curItemId,num = curCount}
            app.session:request("action.C2S_BuyGoods", param, function(msg)
                if msg and checknumber(msg.goods.id) == checknumber(curItemId) then
                    app:popMessage("buySuccess")
                    EM:notify(ViewEvent.AchieveShop_BuyGoods)
                end
                AchievementManager:queryGoods()
            end)
        end)
        display.setBtnTouchEnable(btnBuy, aEnougn)
        -- 设置居中
        display.setNodesMiddle(panelNum, dot, curPrice, goldIcon)
    end 

    local function getShopItem(l, r)
        local ret = self.achShopNode:clone()

        ret:setContentSize(self:seek("Panel", ret):getContentSize())

        ret.left = ret:findChild("Panel/Panel_Left")
        ret.right = ret:findChild("Panel/Panel_Right")

        ret.left:hide()
        ret.right:hide()

        local lbtn = nil
        local rbtn = nil

        local function setGood(panel, data)            
            panel:show()

            panel.iconNode = self:seek("icon", panel)
            panel.name = self:seek("name", panel)
            panel.price = self:seek("num_gold", panel)
            panel.achPoint = self:seek("num_achieve", panel)
            panel.needText = self:seek("Text", panel)

            local itemData = data.itemData
            local itemCount = checknumber(string.split(data.item, "|")[3])

            panel.icon = panel.iconNode:findChild("Panel/icon")--self:seek("icon", panel.iconNode)
            panel.icon:loadTexture(itemData:getIcon())
            panel.iconNode:findChild("Panel/level"):hide()
            panel.iconNode:findChild("Panel/selected"):hide()
            panel.frameNode = panel.iconNode:findChild("Panel/grade")
            panel.frameNode:loadTexture(itemData:getIconBg())            

            panel.iconNode:findChild("Panel/Panel_num/num"):setString(itemCount)

            if data.name then
                panel.name:setString(L(data.name))
            else
                panel.name:setString(itemData:getName())
            end
            for i = 1, 3 do
                panel:getChildByName("icon_"..i):setVisible(false)
            end
            local costList = string.split(data.cost, ";")
            if #costList == 1 then
                local cost = string.split(costList[1], "|")
                panel.price:setString(checknumber(cost[3]))
                panel.price:setVisible(true)
                local itemData = UD:parseLootToBagItem({type = cost[1], id = cost[2], num = cost[3]})
                if itemData and itemData.getIcon then
                    panel:findChild("Panel_bg/icon_gold"):setVisible(true)
                    panel:findChild("Panel_bg/icon_gold"):loadTexture(itemData:getIcon())
                end
            else
                panel.price:setVisible(false)
                panel:findChild("Panel_bg/icon_gold"):setVisible(false)
                -- 多个道具购买
                for i, costData in ipairs(costList) do
                    local cost = string.split(costData, "|")
                    local item = UD:parseLootToBagItem({type = tonumber(cost[1]), id = tonumber(cost[2]), num = tonumber(cost[3])})
                    local iconNode = panel:getChildByName("icon_"..i)
                    local iconNumNode = iconNode:getChildByName("num")
                    if iconNode then
                        iconNode:loadTexture(item:getIcon())
                        iconNumNode:setString(item.amount)
                        iconNode:setVisible(true)
                    end
                end
            end
            local apCondition = 0
            local idCondition = 0
            local condType = 0

            if data.buyCondition then
                local cs = string.split(data.buyCondition, "|")
                condType = checknumber(cs[1])
                if condType == 6 then --成就点数
                    apCondition = checknumber(cs[2])
                elseif condType == 4 then --成就id
                    idCondition = checknumber(cs[2])
                end
            end
            
            local unlocked = false
            local function setconditions()
                if condType == 6 and checknumber(apCondition) > UD.player.achievementPoint then
                    panel.needText:setString(L("lua_code_text_196"))
                    panel.achPoint:setString(tostring(apCondition))
                elseif condType == 4 and not AchievementManager:isAchievementFinished(checknumber(idCondition)) then
                    panel.needText:setString(L"achshop_cond_achid")
                    panel.achPoint:setString(L(AchievementManager.achMap[checknumber(idCondition)].name))
                    panel.achPoint:setPositionX(panel.achPoint:getPositionX()-48)
                else
                    panel.achPoint:hide()
                    unlocked = true
                end

                if unlocked then                
                    local limiCnt = 1
                    if AchievementManager.servergoods and AchievementManager.servergoods[checknumber(data.ID)] then
                        local sd = AchievementManager.servergoods[checknumber(data.ID)]
                        limiCnt = checknumber(sd.leftNum)
                    else
                        limiCnt = 0
                    end    
                    panel.needText:setString(string.format(L("lua_code_text_42"), tostring(limiCnt)))
                end
            end
            setconditions()

            local function bgclick()
                curCondition = apCondition
                curConditionType = condType
                if condType == 4 then curCondition = idCondition end
                setCurrentItem(data.itemId, data, self:seek("Button_bg", panel), unlocked)
            end
            panel.iconNode:findChild("Panel"):setTouchEnabled(false)
            self:seek("Button_bg", panel):addTouchEventListener(function(sender, eventType)
                if eventType == ccui.TouchEventType.ended then
                    bgclick()     
                end
            end )

            self:seek("Button_bg", panel).bgclick = bgclick

            return self:seek("Button_bg", panel)
        end
        
        if l then
            lbtn = setGood(ret.left, l)
        end

        if r then
            rbtn = setGood(ret.right, r)
        end

        return ret , lbtn, rbtn
    end 

    local function refreshShopPanel()
        currentBtn = nil
        local lv = self.panelShop:findChild("Panel/ListView")
        local items = AchievementManager:getAchievementShopItems()        
        local index = 1
        local lbtn , rbtn, selectbtn
        self._curRender = nil

        if #items == 0 then
            self.showShop(false)
        else
            self.showShop(true)
        end        

        -- 商店名字
        self.panelShop:findChild("Panel/Panel_tlt/tlt"):setString(AchievementManager:getShopName())

        lv:removeAllChildren()
        while (items[index]) do
            local item , l, r = getShopItem(items[index], items[index + 1])
            if index == 1 then
                lbtn = l 
                rbtn = r
            end
            if self._itemInfo ~= nil then
                local tempItem1 = string.split(items[index].item, "|")
                local tempItem2 = ""
                if items[index+1] then
                    tempItem2 = string.split(items[index+1].item, "|")
                end
                if (tempItem1 and self._itemInfo[1] == tonumber(tempItem1[1]) and self._itemInfo[2] == tonumber(tempItem1[2]))
                 or (tempItem2 and self._itemInfo[1] == tonumber(tempItem2[1]) and self._itemInfo[2] == tonumber(tempItem2[2])) then
                    self._curRender = item
                    if self._itemInfo[1] == tonumber(tempItem1[1]) and self._itemInfo[2] == tonumber(tempItem1[2]) then
                        selectbtn = l
                    else
                        selectbtn = r
                    end
                end
            end
            lv:pushBackCustomItem(item)
            index = index + 2
        end
        lv:requestRefreshView()
        lv:forceDoLayout()
        if self._curRender ~= nil then
            local off = lv:getInnerContainerSize().height - lv:getContentSize().height
			if off > 0 then
				local off2 = math.max(0, off - (lv:getInnerContainerSize().height - math.abs(self._curRender:getPositionY() + self._curRender:getContentSize().height)))
                lv:jumpToPercentVertical(math.max(0, math.min(100, 100 * (1-off2/off))))
            end
            self._itemInfo = nil
            self._curRender = nil
        else
            lv:jumpToTop()
        end
        if selectbtn then
            selectbtn.bgclick()
        elseif lbtn then
            lbtn.bgclick()
        end
    end
    refreshShopPanel()
    
    EM:on(AchievementManager.GoodsChangeEventName, function()      
        refreshShopPanel()
    end)
end 

function AchView:showShopRedPoint(b)
    -- local d = self.mUINode:findChild("Panel/Panel_tab/selected_btn_2/dot")
    -- d:setVisible(b)
end

function AchView:refreshShopRedPoint()
    local items = AchievementManager:getAchievementShopItems()
    local canBuyCount = 0
    for i, v in ipairs(items) do
        local apCondition = 0
        local condType = 0
        if v.buyCondition then
            apCondition = checkint(string.split(v.buyCondition, "|")[2])
            condType = checkint(string.split(v.buyCondition, "|")[1])
        end

        if condType == 6 and apCondition <= UD.player.achievementPoint then
            canBuyCount = canBuyCount + 1
        elseif condType == 4 and AchievementManager:isAchievementFinished(apCondition) then
            canBuyCount = canBuyCount + 1
        end
    end

    if checknumber(AchievementManager.canBuyCount) < canBuyCount then
        self:showShopRedPoint(true)
    end

    AchievementManager.tempCanBuyCount = canBuyCount
end

return AchView
